package cn.dapeng.thread.delayedQueue;

/**
 * @BelongProject study
 * @BelongPackage cn.dapeng.thread.delayedQueue
 * @Description 环形数组
 * @ClassName RingArray
 * @Author xupenghong
 * @Date 2024/8/28 14:12
 * @Version 1.0.0
 */
public class RingArray<E> {

    private final Object[] element;
    private final int capacity;
    private int head, tail, size;

    RingArray(int capacity) {
        this.capacity = capacity;
        this.size = 0;
        this.head = -1;
        this.tail = 0;
        element = new Object[capacity];
    }

    public void addToTail(E ele) {
        if (size < capacity) {
            head = (head + 1) == capacity ? 0 : head + 1;
            element[head] = ele;
            size++;
        }
    }

    public E removeFromTail() {
        E ele = null;
        if (size > 0) {
            ele = (E) element[tail];
            element[tail] = null;
            tail = (tail + 1) == capacity ? 0 : tail + 1;
            size--;
        }
        return ele;
    }

    public void clear() {
        for (int i = 0; i < capacity; i++) element[i] = null;
    }

    public E peek() {
        return (E) element[tail];
    }

    public int getSize() {
        return size;
    }

    public void print() {
        for (int i = 0; i < capacity; i++) {
            if (element[i] != null) System.out.print(element[i] + ", ");
        }
        System.out.println();
    }

    @Override
    public String toString() {
        return this.size + " from " + this.head + " to " + this.tail;
    }

}
